package com.ndkj.blog.aspect;

import com.ndkj.blog.mapper.BlogMapper;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/***
 * @author liuyong
 * @date 2021/7/27 15:08
 * @description: 本类注册为切面类，在所有请求响应之前执行
 * 逻辑：若是新用户访问本站，那么让数据库的AccessNum自增，之后5分钟内该用户再次访问会执行判断session是否为空，为空则不再执行AccessNum自增操作
 */
@Component
@Aspect
public class AccessNum {

    @Autowired
    private BlogMapper blogMapper;

    @Before("execution(* com.ndkj.blog.controller.*.*(..))")
    public void accessNum() {
        //获取request
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        //设置session的超时时间为30分钟
        request.getSession().setMaxInactiveInterval(1800);
        //判断用户的session是否为空。若为空则为session赋值并将本站阅读量自增
        if (request.getSession().getAttribute("session") == null) {
            request.getSession().setAttribute("session", "sessionIsExist");
            blogMapper.addAccessNum();
        }
    }
}
